<template>
  <div>
    <div
      style="
        display: flex;
        position: fixed;
        top: 10px;
        left: 63px;
        z-index: 999;
      "
    >
      <v-btn @click="btn"> 保存 </v-btn>
      <v-btn @click="dialog = true"> 登录 </v-btn>
      <v-btn @click="exportToExcel"> 导出 </v-btn>
    </div>
    <div id="luckysheet"></div>
    <div v-show="isMaskShow" id="tip">Downloading</div>
  </div>
  <div class="pa-4 text-center">
    <v-dialog v-model="dialog" max-width="1200">
      <v-card class="mx-auto px-6 py-8" max-width="1300">
        <v-form style="width: 300px" v-model="form" @submit.prevent="onSubmit">
          <v-text-field
            v-model="email"
            :readonly="loading"
            :rules="[required]"
            class="mb-2"
            label="Email"
            clearable
          ></v-text-field>

          <v-text-field
            v-model="password"
            :readonly="loading"
            :rules="[required]"
            label="Password"
            placeholder="Enter your password"
            clearable
          ></v-text-field>

          <br />

          <v-btn
            :disabled="!form"
            :loading="loading"
            color="success"
            size="large"
            type="submit"
            variant="elevated"
            block
          >
            Sign In
          </v-btn>
        </v-form>
      </v-card>
    </v-dialog>
  </div>
  <!-- <div style="position: absolute; top: 0">
    <input id="uploadBtn" type="file" @change="loadExcel" />

    <span>Or Load remote xlsx file:</span>

    <select v-model="selected" @change="selectExcel">
      <option disabled value="">Choose</option>
      <option
        v-for="option in options"
        :key="option.text"
        :value="option.value"
      >
        {{ option.text }}
      </option>
    </select>

    <a href="javascript:void(0)" @click="downloadExcel"
      >Download source xlsx file</a
    >
  </div> -->
</template>

<script setup>
import { ref, onMounted } from "vue";
import { exportExcel } from "../utils/export";
import { isFunction } from "../utils/is";
import LuckyExcel from "luckyexcel";
import * as XLSX from "xlsx";

const isMaskShow = ref(false);
const dialog = ref(false);
const selected = ref("");
const jsonData = ref({});
const form = ref(false);
const email = ref("");
const password = ref("");
const loading = ref(false);

const required = (v) => {
  return !!v || "Field is required";
};

const loadExcel = (evt) => {
  const files = evt.target.files;
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }

  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != "xlsx") {
    alert("Currently only supports the import of xlsx files");
    return;
  }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson);
      jsonData.value = exportJson;

      isFunction(window?.luckysheet?.destroy) && window.luckysheet.destroy();

      window.luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};

const onSubmit = () => {
  if (!form) return;

  loading.value = true;
  auth();
  setTimeout(() => (loading.value = false), 2000);
};
const auth = () => {
  $.ajax({
    type: "POST",
    url:
      "http://localhost:3000/api/auth/oauth/token?grant_type=password&username=" +
      email.value +
      "&password=" +
      password.value,
    headers: {
      Authorization: "Basic YXBwOmFwcA==",
    },
    success: function (e) {
      console.log(e);
      localStorage.setItem("auth", JSON.stringify(e));
    },
  });
};
const btn = (e) => {
  let datas = luckysheet.getAllSheets()[0].celldata;
  console.log(datas);
  $.post(
    "http://127.0.0.1:9004/luckysheet/api/order?subGroupNo=" +
      // "http://106.14.166.162:9004/luckysheet/api/order?subGroupNo=" +
      getQueryVariable("gno"),
    { data: JSON.stringify(datas) },
    function (d) {
      console.log(d);
    }
  );
};
const selectExcel = (evt) => {
  const value = selected.value;
  const name = evt.target.options[evt.target.selectedIndex].innerText;

  if (value == "") {
    return;
  }
  isMaskShow.value = true;

  LuckyExcel.transformExcelToLuckyByUrl(
    value,
    name,
    (exportJson, luckysheetfile) => {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson);
      jsonData.value = exportJson;

      isMaskShow.value = false;

      isFunction(window?.luckysheet?.destroy) && window.luckysheet.destroy();

      window.luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};
const downloadExcel = () => {
  // const value = selected.value;;
  //
  // if(value.length==0){
  //     alert("Please select a demo file");
  //     return;
  // }
  //
  // var elemIF = document.getElementById("Lucky-download-frame");
  // if(elemIF==null){
  //     elemIF = document.createElement("iframe");
  //     elemIF.style.display = "none";
  //     elemIF.id = "Lucky-download-frame";
  //     document.body.appendChild(elemIF);
  // }
  // elemIF.src = value;
  exportExcel(luckysheet.getAllSheets(), "下载");
};

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

function exportToExcel() {
  // 获取所有表格数据
  const sheets = luckysheet.getAllSheets();

  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  // 遍历所有表格
  // sheets.forEach(sheet => {
  //   // 将 Luckysheet 表格数据转换为 Excel 工作表
  //   const worksheet = XLSX.utils.aoa_to_sheet(sheet.data);
  //   // 设置工作表名称
  //   XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name);
  // });
  // 遍历数据，将日期格式转换为字符串
  let data = sheets[0].data;
  console.log(data);
  data.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      console.log(cell);
      if (cell && cell.ct.t === "d") {
        // 将日期转换为字符串
        console.log(cell.v);
        cell.v = cell.m;
        cell.ct.t = "g"; // 设置单元格类型为字符串
      }
    });
  });

  const worksheet = XLSX.utils.aoa_to_sheet(data);
  // 设置工作表名称
  XLSX.utils.book_append_sheet(workbook, worksheet, sheets[0].name);
  // 将工作簿转换为二进制数据
  const excelData = XLSX.write(workbook, { bookType: "xlsx", type: "array" });

  // 创建一个 Blob 对象
  const blob = new Blob([excelData], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });

  // 创建一个下载链接
  const url = URL.createObjectURL(blob);

  // 创建一个下载按钮并模拟点击
  const a = document.createElement("a");
  a.href = url;
  a.download = "exported_data.xlsx";
  document.body.appendChild(a);
  a.click();

  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
// !!! create luckysheet after mounted
onMounted(() => {
  var lang = luckysheetDemoUtil.language() === "zh" ? "zh" : "en";
  var isShare = luckysheetDemoUtil.getRequest().share; //Add the '?share' parameter to the url, open the collaborative editing mode
  var options = null;

  options = {
    container: "luckysheet",
    lang: lang,
    allowUpdate: false,
    updateImageUrl: "http://127.0.0.1:9004" + "/luckysheet/api/updateImg",
    updateUrl: "ws://" + "127.0.0.1:9004" + "/luckysheet/websocket/luckysheet",
    // updateImageUrl: "http://106.14.166.162:9004" + "/luckysheet/api/updateImg",
    // updateUrl:
    //   "ws://" + "106.14.166.162:9004" + "/luckysheet/websocket/luckysheet",
    gridKey: "1079500#-8803#7c45f52b7d01486d88bc53cb17dcd2c3",
    loadUrl:
      "http://127.0.0.1:9004" +
      "/luckysheet/api/load?gno=" +
      getQueryVariable("gno"),
    loadSheetUrl: "http://127.0.0.1:9004" + "/luckysheet/api/loadsheet",
    // loadUrl:
    //   "http://106.14.166.162:9004" +
    //   "/luckysheet/api/load?gno=" +
    //   getQueryVariable("gno"),
    // loadSheetUrl: "http://106.14.166.162:9004" + "/luckysheet/api/loadsheet",
    hook: {
      cellDragStop: function (cell, postion, sheetFile, ctx, event) {
        // console.info(cell, postion, sheetFile, ctx, event);
      },
      rowTitleCellRenderBefore: function (rowNum, postion, ctx) {
        // console.log(rowNum);
      },
      rowTitleCellRenderAfter: function (rowNum, postion, ctx) {
        // console.log(ctx);
      },
      columnTitleCellRenderBefore: function (columnAbc, postion, ctx) {
        // console.log(columnAbc);
      },
      columnTitleCellRenderAfter: function (columnAbc, postion, ctx) {
        // console.log(postion);
      },
      cellRenderBefore: function (cell, postion, sheetFile, ctx) {
        // console.log(cell,postion,sheetFile,ctx);
      },
      cellRenderAfter: function (cell, postion, sheetFile, ctx) {
        // console.log(postion);
      },
      cellMousedownBefore: function (cell, postion, sheetFile, ctx) {
        // console.log(postion);
      },
      cellMousedown: function (cell, postion, sheetFile, ctx) {
        // console.log(sheetFile);
      },
      sheetMousemove: function (cell, postion, sheetFile, moveState, ctx) {
        // console.log(cell,postion,sheetFile,moveState,ctx);
      },
      sheetMouseup: function (cell, postion, sheetFile, moveState, ctx) {
        // console.log(cell,postion,sheetFile,moveState,ctx);
      },
      cellAllRenderBefore: function (data, sheetFile, ctx) {
        // console.info(data,sheetFile,ctx)
      },
      updated: function (operate) {
        // console.info(operate)
      },
      cellUpdateBefore: function (r, c, value, isRefresh) {
        // console.info('cellUpdateBefore',r,c,value,isRefresh)
      },
      cellUpdated: function (r, c, oldValue, newValue, isRefresh) {
        console.info("cellUpdated", r, c, oldValue, newValue, isRefresh);
        newValue.upd = true;
      },
      sheetActivate: function (index, isPivotInitial, isNewSheet) {
        // console.info(index, isPivotInitial, isNewSheet)
      },
      rangeSelect: function (index, sheet) {
        // console.info(index, sheet)
      },
      commentInsertBefore: function (r, c) {
        // console.info(r, c)
      },
      commentInsertAfter: function (r, c, cell) {
        // console.info(r, c, cell)
      },
      commentDeleteBefore: function (r, c, cell) {
        // console.info(r, c, cell)
      },
      commentDeleteAfter: function (r, c, cell) {
        // console.info(r, c, cell)
      },
      commentUpdateBefore: function (r, c, value) {
        // console.info(r, c, value)
      },
      commentUpdateAfter: function (r, c, oldCell, newCell) {
        // console.info(r, c, oldCell, newCell)
      },
      cellEditBefore: function (range) {
        // console.info(range)
      },
      workbookCreateAfter: function (json) {
        console.info("workbook create after!!!!====", json);
      },
      rangePasteBefore: function (range, data) {
        // console.info('rangePasteBefore',range,data)
        // return false; //Can intercept paste
      },
      rangeDeleteBefore: function (range, data) {
        console.dir(111);
      },
    },
  };

  luckysheet.create(options);

  setTimeout(() => {
    console.log(luckysheet.getAllSheets());
    console.info($.post);
  }, 3000);
});
</script>

<style scoped>
#luckysheet {
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 100%;
  left: 0px;
  top: 0px;
  bottom: 0px;
}

#uploadBtn {
  font-size: 16px;
}

#tip {
  position: absolute;
  z-index: 1000000;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  background: rgba(255, 255, 255, 0.8);
  text-align: center;
  font-size: 40px;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>
